<?php
/**
 * Service class.
 *
 * @package SGN_SMS
 * @version $Id: Service.php 1597 2012-10-12 04:09:18Z tamlt2 $
 * @author tamlt2 $
 *
 */
class SGN_SMS_Service
{    
    /**
     *
     * @var $_instance
     */
    private static $_instance = null;
    
    /**
     * Config
     */
    private $_config = null;
    
    /**
     * Singleton pattern.
     *
     * @return SGN_SMS_Service
     */
    public static function getInstance()
    {
        if (self::$_instance === null)
            self::$_instance = new self();
        return self::$_instance;
    }
    
    /**
     * Constructor 
     */
    private function __construct()
    {
        /**
         * Get Config
         */
        $this->_config = SGN_Application::getConfig('sgn', 'sms', 'service');
    }
    
    /**
     * Send sms message to a user by his/her userId
     * 
     * @param integer $userId
     * @param string $message 
     * 
     * @return integer, referrence SGN_ECD
     */
    public function sendSMSByUserId($userId, $message)
    {
        $modProfile = Application_Model_SGN_Profile::factory($userId);
        $accountDetail = $modProfile->getAccountDetail();
        if(!$accountDetail['phoneNo']){
            return SGN_ECD::PHONE_NO_NOT_EXIST;
        }
        $phoneNo = $accountDetail['phoneNo'];
        if(!$accountDetail['isPhoneNoVerified']){
            return SGN_ECD::PHONE_NO_NOT_VERIFIED;
        }
        $validate = SGN_SMS_Validate::getInstance();
        if(!$validate->checkNumber($phoneNo)){
            return SGN_ECD::PHONE_NO_NOT_VALID;
        }
        
        $message = '(' . SGN_Application::getConfig('sgn', 'sms', 'signature') . ') ' . $message;
        
        if(strlen($message) > $this->_config->message->maxlength){
            return SGN_ECD::SMS_MESSAGE_TOO_LONG;
        }
        
        $result = $this->sendSMS($phoneNo, $message);
        if($result[code] != 1){
            return SGN_ECD::SEND_SMS_FAILED;
        }
        return 1;
    }

    /**
     * 
     */
    public function sendSMS($number, $message)
    {
        /**
         * Define return Message
         */
        $result = array();
        /**
         * Validate Number
         */
        $validate = SGN_SMS_Validate::getInstance();
        $number = $validate->checkNumber($number); 
        if(!$number) {
            /**
             * Return false Number
             */
            $result['code'] = '0'; 
            $result['errMsg'] = 'phone numbers not validated.';
            return $result;
        }
        
        /**
         * Check Message
         */
        if(strlen($message) > $this->_config->message->maxlength) {
            /**
             * Return false Number
             */
            $result['code'] = '0'; 
            $result['errMsg'] = 'over length of sms message.';
            return $result;
        }
        
        /**
         * Get Micro Date Time
         */
        list($usec, $sec) = explode(" ", microtime()); 
        $timeSec = explode(".", ((float)$usec + (float)$sec));
        $timeMicro = date("ymdGis", $timeSec[0])."".substr($timeSec[1], 0, 3);
        /**
         * Initialize SMS Service
         */
        $smsData = array();
        $smsData['requestID'] = $this->_config->config->requestId . $timeMicro;
        $smsData['userID'] = $number;
        $smsData['serviceID'] = $this->_config->config->serviceId;
        $smsData['commandCode'] = $this->_config->config->commandCode;
        // Message
        $message = SGN_String::utf82ascii($message);
        $smsData['message'] = base64_encode($message);
        //$smsData['secretKey'] = $this->_config->config->secretKey;
        // MD5(requestID + userID + serviceID + commandCode + message + secretKey)
        // requestID -> userID -> serviceID -> commandeCode - > message -> sig 
        $sig = $smsData['requestID'] . $smsData['userID'] . $smsData['serviceID'] . $smsData[ 'commandCode'] . $message . $this->_config->config->secretKey;
        $smsData['sig'] = md5($sig);
        /**
         * Init Soap Client
         */
        $wsdlUrl = $this->_config->config->wsdl;
        $operator = $this->_config->config->operator;
        try {
            $client = new SoapClient($wsdlUrl);
            $return = $client->__soapCall($operator, $smsData);
            // Return
            $result['code'] = $return;
            $smsData['sigString'] = $sig; 
            $result['errMsg'] = $smsData;
            // Return Result
            return $result;
        } catch (Exception $e) {
            $result['code'] = '0'; 
            $result['errMsg'] = 'Caught exception: '.  $e->getMessage(). "\n";
            return $result;
        }
    }
}